package com.ai.module.user.controller;

import cn.hutool.http.*;
import com.ai.module.chat.common.ano.NoAuth;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.user.constant.WXConstant;
import com.ai.module.user.domain.req.UserConfigReq;
import com.ai.module.user.domain.req.UserLogin;
import com.ai.module.user.domain.req.WXUserInfo;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.user.enu.VipType;
import com.ai.module.user.service.UserMangeService;
import com.ai.common.BaseResp;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: MrHe
 * @create: 2023-09-02 12:14
 * @description:
 **/
@RestController
@Slf4j
@RequestMapping("/member/user")
@Api(tags = "用户信息")
public class UserController {
    @Autowired
    private UserMangeService userService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public UserLoginInfo login(@RequestBody UserLogin userLogin){
       return userService.login(userLogin);
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public UserLoginInfo register(@RequestBody UserLogin userLogin, @PathParam("inviteCode")String inviteCode){
        if (StringUtils.isNotBlank(inviteCode) && ! "undefined".equalsIgnoreCase(inviteCode)){
            userLogin.setInviteCode(inviteCode);
        }
        return userService.register(userLogin);
    }


    @GetMapping("/userInfo")
    @NoAuth
    @ApiOperation("查询用户最新信息,强制刷新数据")
    public UserLoginInfo userInfo(){
        return userService.userInfo();
    }


    @PostMapping("/updateUser")
    @ApiOperation("修改用户信息")
    public void updateUser(@RequestBody UserConfigReq userConfigReq){
          userService.updateUser(userConfigReq);
    }

    @GetMapping("/loginOut")
    @ApiOperation("用户退出")
    public void loginOut(){
        userService.loginOut();
    }


    @GetMapping("/membership")
    @ApiOperation("开通VIP")
    public void activateMembership(VipType vipType){
        userService.activateMembership(vipType);
    }


    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/wxPhone")
    @NoAuth
    public UserLoginInfo getPhone(String code) {
        // 获取token
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXConstant.APPID, WXConstant.SECRET);
        JSONObject token = JSON.parseObject(HttpUtil.get(token_url));

        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        // WxOrderServiceImpl.getUserInfo(code);
        // 获取用户的 openId
        JSONObject response = restTemplate.postForObject(url, JSONObject.toJSONString(paramMap), JSONObject.class);
        JSONObject phoneInfo = response.getJSONObject("phone_info");
        log.info("微信登录返回值[{}],参数[{}]",response,code);
        if(phoneInfo==null || phoneInfo.isEmpty()){

            throw new BusinessException("已过期,登录失败");
        }
        String phoneNumber = phoneInfo.getString("phoneNumber");
        String purePhoneNumber = phoneInfo.getString("purePhoneNumber");
        String phone= StringUtils.isBlank(purePhoneNumber)? phoneNumber: purePhoneNumber;
        return userService.loginByWx(phone, code, token);

    }

    @NoAuth
    @PostMapping("wxUserInfo")
    public UserLoginInfo wxUserInfo(@RequestBody WXUserInfo userInfo){

        return userService.wxUserInfo(userInfo);
    }

    @NoAuth
    @PostMapping("sendMessage")
    public BaseResp sendMessage(@RequestBody UserLogin userInfo){

        return userService.sendMessage(userInfo);
    }


}
